package com.mofang.powerdekorhelper.activity.customer;

import android.app.Dialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.mofang.powerdekorhelper.R;
import com.mofang.powerdekorhelper.base.MvpActivity;
import com.mofang.powerdekorhelper.model.CommunicateInfo;
import com.mofang.powerdekorhelper.model.ResultMessage;
import com.mofang.powerdekorhelper.persenter.AddCommunicationRecordPersenter;
import com.mofang.powerdekorhelper.utils.DateUtils;
import com.mofang.powerdekorhelper.utils.DialogUtils;
import com.mofang.powerdekorhelper.utils.ParamsUtils;
import com.mofang.powerdekorhelper.utils.SharePerforenceUtils;
import com.mofang.powerdekorhelper.utils.T;
import com.mofang.powerdekorhelper.view.AddCommunicationRecordView;
import com.mofang.powerdekorhelper.witget.TitleBar;

import org.feezu.liuli.timeselector.TimeSelector;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mofang.powerdekorhelper.R.id.add_record_time_start_tv;

/**
 * Created by luofei on 2017/8/30 0030.
 * 说明：
 */

public class AddCommunicationRecordActivity extends MvpActivity<AddCommunicationRecordView, AddCommunicationRecordPersenter> implements
        AddCommunicationRecordView {

    @BindView(R.id.add_record_titlebar)
    TitleBar mTitleBar;

    @BindView(R.id.add_record_state_sp)
    Spinner stateSp;

    @BindView(R.id.add_record_gender_sp)
    Spinner genderSp;

    @BindView(R.id.add_record_age_edit)
    EditText ageEdit;

    @BindView(R.id.add_record_install_area_edit)
    EditText areaEdit;

    @BindView(R.id.add_record_hourse_area_edit)
    EditText hourseAreaEdit;

    @BindView(R.id.add_record_install_mode_edit)
    EditText modeEdit;

    @BindView(add_record_time_start_tv)
    TextView timeStartTv;

    @BindView(R.id.add_record_install_time_start_tv)
    TextView installStartTimeTv;

    @BindView(R.id.add_record_install_time_end_tv)
    TextView installEndTimeTv;

    @BindView(R.id.add_record_communication_edit)
    EditText communicationEdit;

    private DialogUtils dialogUtils;

    String mTime;

    Integer customerId;
    Integer userId;

    String startTime = "";
    String gender = "";
    String state = "";
    Integer stateIntFlag;
    Integer genderInt;

    List<String> stateList;
    List<String> genderList;

    TimeSelector timeSelector;

    Dialog chooseTimeDialog;

    @Override
    public void initView() {
        inflateLayout(R.layout.activity_add_communication_record_layout);
        initTitleBar();
    }

    @Override
    public void initData() {

        customerId = getIntent().getIntExtra("CustomerId", -1);
        userId = SharePerforenceUtils.getInstance(this).getUserID();

        stateList = new ArrayList<>();

        stateList.add("请选择");
        stateList.add("已联系");
        stateList.add("已进店");
        stateList.add("已购卡");
        stateList.add("已订单");
        stateList.add("已活动");
        stateList.add("已物流");
        stateList.add("已安装");
        stateList.add("售后中");
        stateList.add("已关闭");

        ArrayAdapter<String> statePadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stateList);
        statePadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        stateSp.setAdapter(statePadapter);

        genderList = new ArrayList<>();
        genderList.add("请选择");
        genderList.add("男");
        genderList.add("女");
        ArrayAdapter<String> genderPadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, genderList);
        genderPadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        genderSp.setAdapter(genderPadapter);

        genderSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                gender = genderList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        stateSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                state = stateList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        state = stateSp.getAdapter().getItem(0).toString();
        gender = genderSp.getAdapter().getItem(0).toString();

        presenter.getCommunicateInfo(customerId, userId);
    }

    @Override
    public void setCommunicateInfo(CommunicateInfo communicateInfo) {

        if (communicateInfo.getResult() != null) {

            startTime = DateUtils.getMin(communicateInfo.getResult().getCommunicate_time_start());
            timeStartTv.setText(startTime);
            areaEdit.setText(communicateInfo.getResult().getErection_space() + "");
            hourseAreaEdit.setText(communicateInfo.getResult().getFloor_space() + "");

            long installTimeStart = communicateInfo.getResult().getInstallation_time_start();
            if (installTimeStart != 0) {
                installStartTimeTv.setText(DateUtils.getMin(installTimeStart));
            } else {
                installStartTimeTv.setText("未定");
            }
            long installTimeEnd = communicateInfo.getResult().getInstallation_time_end();
            if (installTimeEnd != 0) {
                installEndTimeTv.setText(DateUtils.getMin(installTimeEnd));
            } else {
                installEndTimeTv.setText("未定");
            }

            modeEdit.setText(communicateInfo.getResult().getInstall_style() + "");
            ageEdit.setText(communicateInfo.getResult().getAge() + "");

            genderInt = communicateInfo.getResult().getGender();

            genderList.clear();
            if (genderInt == 1) {
                genderList.add("男");
                genderList.add("女");
            } else {
                genderList.add("女");
                genderList.add("男");
            }
            ArrayAdapter<String> genderPadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, genderList);
            genderPadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            genderSp.setAdapter(genderPadapter);
            //           }

        }
    }

    @Override
    public void setAddCommunicate(ResultMessage resultMessage) {
        toast("提交成功");
        hideProgress();
        finish();
    }

    @OnClick({add_record_time_start_tv, R.id.add_record_install_time_start_tv, R.id.add_record_install_time_end_tv})
    void onclick(View v) {

        switch (v.getId()) {

            case add_record_time_start_tv:

                getTime(1);
                break;

            case R.id.add_record_install_time_start_tv:

                showChooseTimeDialog("预计开始安装时间", 3);
                break;

            case R.id.add_record_install_time_end_tv:

                if (getinstallStartTime().equals("未定")) {

                } else {
                    if (getinstallStartTime().equals("")) {
                        showChooseTimeDialog("预计开始安装时间", 4);
                    } else {
                        getTime(4);
                    }
                }
                break;
        }
    }

    private String getinstallStartTime() {
        return installStartTimeTv.getText().toString();
    }

    private String getinstallEndTime() {
        return installEndTimeTv.getText().toString();
    }

    private void showChooseTimeDialog(String title, final int flag) {
        dialogUtils = DialogUtils.getInstance();
        chooseTimeDialog = dialogUtils.chooseTimeDialog(AddCommunicationRecordActivity.this, title, new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                switch (v.getId()) {

                    case R.id.commit_dialog_undecided_tv:

                        if (flag == 3) {

                            installStartTimeTv.setText("未定");
                            installEndTimeTv.setText("未定");
                        } else {

                            installStartTimeTv.setText("未定");
                            installEndTimeTv.setText("未定");
                        }
                        break;

                    case R.id.commit_dialog_sure_tv:

                        getTime(flag);
                        break;

                    case R.id.commit_dialog_cancle_imv:

                        break;
                }

                chooseTimeDialog.dismiss();
            }
        });

        chooseTimeDialog.show();
    }

    private void getTime(final int flag) {

        String date;

        if (flag == 1) {
            date = startTime;
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date curDate = new Date(System.currentTimeMillis());
            date = formatter.format(curDate);
        }

        if (date.equals("")) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date curDate = new Date(System.currentTimeMillis());
            date = formatter.format(curDate);
        }

        timeSelector = new TimeSelector(AddCommunicationRecordActivity.this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {

                switch (flag) {
                    case 1:
                        timeStartTv.setText(time);
                        break;
                    case 2:
                        //timeEndTv.setText(time);
                        break;
                    case 3:
                        installStartTimeTv.setText(time);
                        break;
                    case 4:
                        installEndTimeTv.setText(time);
                        break;
                }
            }
        }, date, "2018-12-31 23:59:59");

        timeSelector.setIsLoop(false);

        timeSelector.setMode(TimeSelector.MODE.YMDHM);

        timeSelector.show();

        timeSelector.setTitle("请选择时间");
    }

    public void initTitleBar() {

        initTitleBarWithback(mTitleBar, R.string.add_communication);
        mTitleBar.setActionTextColor(getResources().getColor(R.color.fontcolorpowerdekor));
        mTitleBar.addAction(new TitleBar.TextAction("提交") {
            @Override
            public void performAction(View view) {
                commitInfo();
            }
        });
    }

    private void commitInfo() {

        userId = SharePerforenceUtils.getInstance(this).getUserID();// com.mofang.powerdekorhelper
        String communicateStart = timeStartTv.getText().toString();

        Integer genderFlag;
        if (gender.equals("男")) {
            genderFlag = 1;
        } else {
            genderFlag = 2;
        }
        String age = ageEdit.getText().toString();

        String erectionSpaceStr = areaEdit.getText().toString();
        double erectionSpace = 0;
        if (!erectionSpaceStr.equals("")) {
            erectionSpace = Double.parseDouble(erectionSpaceStr);
        }

        String hourseAreaStr = hourseAreaEdit.getText().toString();
        double hourseArea = 0;
        if (!hourseAreaStr.equals("")) {
            hourseArea = Double.parseDouble(hourseAreaStr);
        }

        String installStart = getinstallStartTime();
        String installEnd = getinstallEndTime();

        String nstallStyle = modeEdit.getText().toString();

        String communicateContent = communicationEdit.getText().toString();

        if (communicateStart.equals("") || hourseAreaStr.equals("") || erectionSpaceStr.equals("") || installStart.equals("")
                || installEnd.equals("") || nstallStyle.equals("") || communicateContent.equals("")) {
            toast("请完善信息");
            return;
        } else {
            dialogUtils = DialogUtils.getInstance();
            dialogUtils.createLoadingDialog(AddCommunicationRecordActivity.this, "正在提交请稍候");
            presenter.getAddCommunicate(ParamsUtils.getAddCommunicateParams(customerId, userId, communicateStart,
                    genderFlag, age, erectionSpace, hourseArea, installStart, installEnd, nstallStyle, communicateContent, state));
        }
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {
        if (dialogUtils != null) {
            dialogUtils.hideLoadingDialog();
        }
    }

    @Override
    public void toast(CharSequence s) {

        T.showShort(this, s);
    }

    @Override
    public void toast(int id) {

    }

    @Override
    public void showNullLayout() {

    }

    @Override
    public void hideNullLayout() {

    }

    @Override
    public void showErrorLayout(View.OnClickListener listener) {

    }

    @Override
    public void hideErrorLayout() {

    }

    @Override
    public void onError(String errorInfo) {
        toast(errorInfo);
        hideProgress();
    }

    @Override
    public AddCommunicationRecordPersenter initPresenter() {
        return new AddCommunicationRecordPersenter();
    }
}
